package top.yuki.Inventory;

import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import top.yuki.Chat.ChatCharacteristic;
import top.yuki.LevelWorld;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;


public class Package {
    private static LevelWorld lw = LevelWorld.instance;
    private static Configuration config = lw.getConfig();

    // 初始化文件
    public static void initFile(File file) {
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (file.length() == 0) {
            FileConfiguration c = YamlConfiguration.loadConfiguration(file);
            c.set("inventory.content", new ItemStack[41]);
            c.set("inventory.enderChest", new ItemStack[36]);
            try {
                c.save(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void backup(File file,int worldLevel,String name){
        File backupFold = new File(lw.getDataFolder()+File.separator+"worldData"+File.separator+"backup.yml");
        if (!backupFold.exists()) {
            backupFold.mkdirs();
        }
        try {
            Files.copy(file.toPath(), Paths.get(backupFold.toPath() + File.separator+"_" + worldLevel+name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //A背包的排除物与B背包合并并写入玩家背包
    public static void joint(int worldLevelA, int worldLevelB, Player p) {
        File fileA = new File(lw.getDataFolder() + File.separator + "worldData" + File.separator + worldLevelA + File.separator + p.getName() + ".yml");
        File fileB = new File(lw.getDataFolder() + File.separator + "worldData" + File.separator + worldLevelB + File.separator + p.getName() + ".yml");
        initFile(fileA);
        initFile(fileB);
//        backup(fileA,worldLevelA,p.getName());
//        backup(fileB,worldLevelB,p.getName());
        boolean canJoint = canJoint(fileA, fileB, p);
        boolean hasEquipmentB = hasEquipment(fileB);
        boolean hasEquipmentA = hasEquipment(fileA);
        FileConfiguration b = YamlConfiguration.loadConfiguration(fileB);

        ItemStack[] content = ((List<ItemStack>) b.get("inventory.content")).toArray(new ItemStack[0]);
        ItemStack[] exclusionType = cutExclusionType(fileA);


        if (hasEquipmentA & !hasEquipmentB) {
            for (int i = exclusionType.length - 5; i < exclusionType.length - 1; i++) {
                content[i] = exclusionType[i];
                exclusionType[i] = null;
            }

        }

        if (canJoint) {
            for (int i = 0; i < content.length; i++) {
                if (content[i] == null) {

                    for (int j = 0; j < exclusionType.length; j++) {
                        if (exclusionType[j] != null) {
                            content[i] = exclusionType[j];
                            exclusionType[j] = null;
                            break;
                        }
                    }
                }
            }
        } else {
            p.sendMessage(ChatCharacteristic.SYSTEM_CAT.system + "背包空间不足，无法传送特殊物品");
            FileConfiguration a = YamlConfiguration.loadConfiguration(fileA);
            ItemStack[] contentA = ((List<ItemStack>) a.get("inventory.content")).toArray(new ItemStack[0]);
            for (ItemStack itemStack : contentA) {
                if (itemStack != null){
                    System.out.println(itemStack.getType());
                }
            }
            for (int i = 0; i < contentA.length; i++) {
                if (contentA[i] != null) {
                    for (int i1 = 0; i1 < exclusionType.length; i1++) {
                        if (exclusionType[i1] != null) {
                            contentA[i] = exclusionType[i1];
                            exclusionType[i1] = null;
                            break;
                        }
                    }
                }
            }
            a.set("inventory.content", contentA);
            try {
                a.save(fileA);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        ItemStack[] newContent = content;
        if (content.length > 41) {
            newContent = new ItemStack[41];
            System.arraycopy(content, 0, newContent, 0, 41);
        }
        p.getInventory().setContents(newContent);
        fileB.delete();
    }

    private static boolean hasEquipment(File f) {
        FileConfiguration c = YamlConfiguration.loadConfiguration(f);
        ItemStack[] content = ((List<ItemStack>) c.get("inventory.content")).toArray(new ItemStack[0]);
        for (int i = content.length - 5; i < content.length - 1; i++) {
            if (content[i] == null) {
                continue;
            } else {
                return true;
            }
        }
        return false;
    }

    // 剪切出排除物
    public static ItemStack[] cutExclusionType(File fileA) {
        FileConfiguration c = YamlConfiguration.loadConfiguration(fileA);
        ItemStack[] content = ((List<ItemStack>) c.get("inventory.content")).toArray(new ItemStack[0]);
        ItemStack[] exclusionType = new ItemStack[41];
        int exclusionAmount = 0;

        //先剪出最后五个中的四个（排除最后一个），放到后面（装备）
        for (int i = content.length - 5; i < content.length - 1; i++) {
            exclusionType[i] = content[i];
            content[i] = null;
        }
        //后剪出其他物品
        for (int i = 0; i < content.length; i++) {
            if (!(content[i] == null)) {
                if (config.getStringList("exclusionType").contains(content[i].getType().toString())) {
                    exclusionType[exclusionAmount] = content[i];
                    exclusionAmount++;
                    content[i] = null;
                }
            }
        }
        c.set("inventory.content", content);
        try {
            c.save(fileA);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return exclusionType;
    }

    //A背包的排除物能否与B背包合并
    public static boolean canJoint(File fileA, File fileB, Player p) {
        try {
            if (!fileB.exists()) {
                fileB.createNewFile();
                return false;
            } else if (!fileA.exists()) {
                fileA.createNewFile();
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        int bAmount = itemAmount(fileB);
        int ExclusionItemAmount = exclusionItemAmount(fileA);
        if (ExclusionItemAmount + bAmount <= 36) {
            return true;
        } else {
            return false;
        }
    }

    private static int exclusionItemAmount(File file) {
        FileConfiguration c = YamlConfiguration.loadConfiguration(file);
        ItemStack[] content = ((List<ItemStack>) c.get("inventory.content")).toArray(new ItemStack[0]);
        ItemStack[] exclusionType = new ItemStack[41];
        int exclusionAmount = 0;
        for (ItemStack itemStack : content) {
            if (!(itemStack == null)) {
                if (config.getStringList("exclusionType").contains(itemStack.getType().toString())) {
                    exclusionType[exclusionAmount] = itemStack;
                    exclusionAmount++;
                }

            }
        }
        return exclusionAmount;
    }

    private static int itemAmount(File file) {
        FileConfiguration c = YamlConfiguration.loadConfiguration(file);
        ItemStack[] content = ((List<ItemStack>) c.get("inventory.content")).toArray(new ItemStack[0]);
        int sum = 0;
        for (ItemStack itemStack : content) {
            if (!(itemStack == null)) {
                sum += 1;
            }
        }
        return sum;
    }

    public static void savePackage(int worldLevel, Player p) {
        File f = new File(lw.getDataFolder() + File.separator + "worldData" + File.separator + worldLevel + File.separator + p.getName() + ".yml");
        FileConfiguration c = YamlConfiguration.loadConfiguration(f);
        c.set("inventory.content", p.getInventory().getContents());

        c.set("inventory.enderChest", p.getEnderChest().getContents());

        try {
            c.save(f);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static ItemStack[] openPackage(int worldLevel, Player p) {
        File f = new File(lw.getDataFolder() + File.separator + "worldData" + File.separator + worldLevel + File.separator + p.getName() + ".yml");
        FileConfiguration c = YamlConfiguration.loadConfiguration(f);
        initFile(f);
        ItemStack[] content = ((List<ItemStack>) c.get("inventory.content")).toArray(new ItemStack[0]);
        return content;


    }


}
